package com.gzx.bi.modular.plan.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gzx.bi.modular.plan.bo.GzxProjectPlanXxlEditBo;
import com.gzx.bi.modular.plan.entity.GzxProjectPlan;
import com.gzx.bi.modular.plan.mapper.GzxProjectPlanMapper;
import com.gzx.bi.modular.plan.service.GzxProjectPlanXxlJobService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.util.CommonDateUtil;

import java.math.BigDecimal;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author zjt
 * @description
 * @date 2025/4/27 16:27
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GzxProjectPlanXxlJobServiceImpl implements GzxProjectPlanXxlJobService {

    private final GzxProjectPlanMapper baseMapper;

    /**
     * 保存上月数据
     * 上月委案金额，上月人力
     */
    @DS("bi")
    @Override
    public void saveLastMonthData() {
        baseMapper.saveLastMonthData(Integer.parseInt(CommonDateUtil.getCurrentMonth()), Integer.parseInt(CommonDateUtil.getLastMonth()));
    }

    /**
     * 修改项目计划数据：保存分公司上报回款金额，甲方还款数据
     *
     * @param projectPlanXxlEditBo
     */
    @DS("bi")
    @Override
    public void modifyRepaymentAmount(GzxProjectPlanXxlEditBo projectPlanXxlEditBo) {
        GzxProjectPlan projectPlan = getGzxMonthlyGoalsForTotal(projectPlanXxlEditBo);
        if (projectPlan != null) {
            //分公司上报还款金额
            if (projectPlanXxlEditBo.getBranchRepay() != null) {
                projectPlan.setBranchRepay(projectPlan.getBranchRepay().add(projectPlanXxlEditBo.getBranchRepay()));
            }
            //当月甲方还款
            if (projectPlanXxlEditBo.getTotalRepay() != null) {
                projectPlan.setTotalRepay(projectPlan.getTotalRepay().add(projectPlanXxlEditBo.getTotalRepay()));
                if (CollectionUtil.isNotEmpty(projectPlanXxlEditBo.getDayRepaymentDetail())) {
                    projectPlan.setRepaymentDetail(setDetailJson(projectPlan.getRepaymentDetail(), projectPlanXxlEditBo.getDayRepaymentDetail()));
                }
            }
            //上月甲方还款
            if (projectPlanXxlEditBo.getLastTotalRepay() != null) {
                projectPlan.setLastTotalRepay(projectPlanXxlEditBo.getLastTotalRepay());
            }
            //昨日甲方还款
            if (projectPlanXxlEditBo.getYesterdayRepay() != null) {
                projectPlan.setYesterdayRepay(projectPlanXxlEditBo.getYesterdayRepay());
            }
            //上月垫付
            if (projectPlanXxlEditBo.getLastAdvance() != null) {
                projectPlan.setLastAdvance(projectPlanXxlEditBo.getLastAdvance());
            }
            //昨日垫付
            if (projectPlanXxlEditBo.getYesterdayAdvance() != null) {
                projectPlan.setYesterdayAdvance(projectPlanXxlEditBo.getYesterdayAdvance());
            }
            baseMapper.updateById(projectPlan);
        }
    }


    private GzxProjectPlan getGzxMonthlyGoalsForTotal(GzxProjectPlanXxlEditBo projectPlanXxlEditBo) {
        GzxProjectPlan projectPlan = baseMapper.selectOne(Wrappers.<GzxProjectPlan>lambdaQuery()
                .eq(GzxProjectPlan::getProjectCode, projectPlanXxlEditBo.getProjectCode())
                .eq(GzxProjectPlan::getBelongingMonth, CommonDateUtil.getCurrentMonth())
                .eq(GzxProjectPlan::getBatch, projectPlanXxlEditBo.getBatch())
                .eq(GzxProjectPlan::getDeptId, projectPlanXxlEditBo.getDeptId()));
        if (projectPlan == null) {
            log.error("发现新项目，但是未添加到项目计划中.........{}", projectPlanXxlEditBo.getProjectCode());
            return null;
        }
        projectPlan.setTotalComm(null);
        projectPlan.setNetComm(null);
        projectPlan.setLastTotalComm(null);
        projectPlan.setLastNetComm(null);
        projectPlan.setRepayDiff(null);
        projectPlan.setAddRepay(null);
        projectPlan.setTaskCompleteRate(null);
        projectPlan.setLastTaskCompleteRate(null);
        projectPlan.setTcrMomDiff(null);
        projectPlan.setYesterdayComm(null);
        projectPlan.setCommCompleteRate(null);
        projectPlan.setLastTaskCompleteRate(null);
        projectPlan.setCommMomDiff(null);
        projectPlan.setPerEntrustCnt(null);
        projectPlan.setLastPerEntrustCnt(null);
        projectPlan.setYesterdayNet(null);
        projectPlan.setEntrustAmt(null);
        projectPlan.setRepayMomDiff(null);
        projectPlan.setEntrustAmtMomDiff(null);
        return projectPlan;
    }

    private String setDetailJson(String detailJson, Map<String, BigDecimal> dayMap) {
        // 将 JSON 字符串解析为 Map，如果解析失败或为空，则初始化一个新的 HashMap
        Map<String, BigDecimal> dsMap = JSON.parseObject(detailJson, Map.class);
        if (dsMap == null) {
            dsMap = new TreeMap<>();
        }
        // 遍历新的 dayMap，将其值合并到 dsMap 中
        for (Map.Entry<String, BigDecimal> day : dayMap.entrySet()) {
            BigDecimal currentAmount = dsMap.getOrDefault(day.getKey(), BigDecimal.ZERO);
            dsMap.put(day.getKey(), currentAmount.add(day.getValue()));
        }
        return JSON.toJSONString(new TreeMap<>(dsMap));
    }
}
